package com.zhangjie.yygh.msm.con_ser;

import com.zhangjie.common.result.Result;
import com.zhangjie.yygh.msm.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //发送验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis获取验证码，如果可以获取到，返回ok
        String code = redisTemplate.opsForValue().get(phone);//key手机号，value放验证码
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果从redis获取不到
        //生成验证码
        code = RandomUtil.getSixBitRandom();
        //调用service，通过整合阿里云短信服务进行发送
        boolean isSend=msmService.send(phone,code);                          //  这里调用service
        //生产验证码放到redis里面，设置有效期
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);
            System.out.println("保存到redis成功，发送到的手机号是："+phone);
            System.out.println("验证码是：  "+redisTemplate.opsForValue().get(phone));
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败!");
        }

    }
}
